<template>
	<uni-popup ref="popupRef" type="center" :mask-click="true" @change="onChange">
		<view class="popup-mask" @click="close">
			<view class="buy-popup" @click.prevent.stop="">
				<!-- 标题 -->
				<text class="popup-title">您正在购买</text>
				<text class="product-name">{{ productInfo.title || 'Pancake Balls' }}</text>
				
				<!-- 进度条 -->
				<view class="progress-section">
					<text class="progress-label">进度</text>
					<view class="progress-container">
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
						</view>
						<text class="progress-text">{{ progressPercent }}%</text>
					</view>
				</view>
				
				<!-- 投资金额输入 -->
				<view class="amount-section">
					<text class="amount-label">请输入购买金额</text>
					<view class="amount-input-container">
						<view class="amount-controls">
							<view class="control-btn" @click="decreaseAmount">-</view>
							<input 
								class="amount-input" 
								type="number" 
								v-model="investAmount" 
								:placeholder="minAmount.toString()"
								@input="onAmountInput"
							/>
							<view class="control-btn" @click="increaseAmount">+</view>
						</view>
					</view>
					<text class="amount-limit">限额: {{ minAmount }}-{{ maxAmount }}</text>
				</view>
				
				<!-- 产品信息 -->
				<view class="product-info-section">
					<view class="info-row">
						<text class="info-label">周期:</text>
						<text class="info-value">{{ productInfo.cycle || '1天' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">收益:</text>
						<text class="info-value">{{ productInfo.rate || '1.3' }}%</text>
					</view>
				</view>
				
				<!-- 确定按钮 -->
				<view class="confirm-btn" @click="confirmPurchase">
					确定
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { TokenManager } from '@/utils/token.js'

const props = defineProps({
	productInfo: {
		type: Object,
		default: () => ({})
	}
})

const emit = defineEmits(['confirm', 'close'])

const popupRef = ref(null)
const investAmount = ref('')

// 计算属性
const progressPercent = computed(() => {
	if (!props.productInfo.progress) return 82
	return Math.round(parseFloat(props.productInfo.progress))
})

const minAmount = computed(() => {
	return parseInt(props.productInfo.minAmount) || 100
})

const maxAmount = computed(() => {
	return parseInt(props.productInfo.maxAmount) || 500
})

// 打开弹窗
const open = () => {
	investAmount.value = minAmount.value.toString()
	popupRef.value?.open()
}

// 关闭弹窗
const close = () => {
	popupRef.value?.close()
	emit('close')
}

// 金额控制
const decreaseAmount = () => {
	const current = parseInt(investAmount.value) || minAmount.value
	const newAmount = Math.max(current - 100, minAmount.value)
	investAmount.value = newAmount.toString()
}

const increaseAmount = () => {
	const current = parseInt(investAmount.value) || minAmount.value
	const newAmount = Math.min(current + 100, maxAmount.value)
	investAmount.value = newAmount.toString()
}

const onAmountInput = (e) => {
	let value = parseInt(e.detail.value) || 0
	if (value < minAmount.value) {
		value = minAmount.value
	} else if (value > maxAmount.value) {
		value = maxAmount.value
	}
	investAmount.value = value.toString()
}

// 确认购买
const confirmPurchase = async () => {
	const amount = parseInt(investAmount.value)
	if (amount < minAmount.value || amount > maxAmount.value) {
		uni.showToast({
			title: `投资金额应在${minAmount.value}-${maxAmount.value}之间`,
			icon: 'none'
		})
		return
	}
	
	try {
		uni.showLoading({
			title: '创建订单中...'
		})
		
		// 调用创建订单接口
		const authHeader = TokenManager.getAuthorizationHeader()
		console.log('Token调试信息:', {
			accessToken: TokenManager.getAccessToken(),
			authHeader: authHeader,
			isLoggedIn: TokenManager.isLoggedIn()
		})
		
		if (!authHeader) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		const response = await uni.request({
			url: '/app-api/invest/pledge-order/create',
			method: 'POST',
			header: {
				'Content-Type': 'application/json',
				'Authorization': authHeader
			},
			data: {
				productId: props.productInfo.id,
				amount: amount,
				startTime: Date.now()
			}
		})
		
		uni.hideLoading()
		
		if (response.data.code === 0) {
			// 订单创建成功
			uni.showToast({
				title: '订单创建成功',
				icon: 'success'
			})
			
			// 触发确认事件，传递订单ID
			emit('confirm', {
				orderId: response.data.data,
				amount: amount,
				productId: props.productInfo.id
			})
			close()
		} else {
			uni.showToast({
				title: response.data.msg || '订单创建失败',
				icon: 'none'
			})
		}
	} catch (error) {
		uni.hideLoading()
		console.error('创建订单失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	}
}

const onChange = (e) => {
	// 弹窗状态变化
}

// 暴露方法给父组件
defineExpose({
	open,
	close
})
</script>

<style scoped lang="scss">
.popup-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 9999;
}

.buy-popup {
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10rpx);
	width: 600rpx;
	max-width: 90vw;
	border-radius: 32rpx;
	padding: 60rpx 40rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
}

.popup-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 10rpx;
}

.product-name {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
}

.progress-section {
	width: 100%;
	margin-bottom: 40rpx;
	
	.progress-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}
	
	.progress-container {
		display: flex;
		align-items: center;
		gap: 20rpx;
		
		.progress-bar {
			flex: 1;
			height: 12rpx;
			background: #f0f0f0;
			border-radius: 6rpx;
			overflow: hidden;
			
			.progress-fill {
				height: 100%;
				background: linear-gradient(90deg, #FFC300 0%, #DEB018 34%, #FF5733 66%, #FF5733 100%);
				border-radius: 6rpx;
				transition: width 0.3s ease;
			}
		}
		
		.progress-text {
			font-size: 24rpx;
			color: #666;
			min-width: 60rpx;
		}
	}
}

.amount-section {
	width: 100%;
	margin-bottom: 40rpx;
	
	.amount-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}
	
	.amount-input-container {
		margin-bottom: 20rpx;
		
		.amount-controls {
			display: flex;
			align-items: center;
			background: #fff;
			border-radius: 50rpx;
			padding: 10rpx;
			border: 2rpx solid #e0e0e0;
			
			.control-btn {
				width: 60rpx;
				height: 60rpx;
				background: #f8f8f8;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
				color: #666;
				user-select: none;
				
				&:active {
					background: #e0e0e0;
				}
			}
			
			.amount-input {
				flex: 1;
				text-align: center;
				font-size: 32rpx;
				color: #333;
				border: none;
				outline: none;
				background: transparent;
			}
		}
	}
	
	.amount-limit {
		font-size: 24rpx;
		color: #999;
		text-align: center;
		display: block;
	}
}

.product-info-section {
	width: 100%;
	margin-bottom: 40rpx;
	
	.info-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.info-label {
			font-size: 28rpx;
			color: #333;
		}
		
		.info-value {
			font-size: 28rpx;
			color: #666;
			font-weight: 500;
		}
	}
}

.confirm-btn {
	width: 100%;
	height: 80rpx;
	background: linear-gradient(90deg, #00D4FF 0%, #00A8E6 100%);
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #fff;
	font-weight: 500;
	
	&:active {
		opacity: 0.8;
	}
}
</style>